<template>
    <div class="alarmConfiguration zy-content ">

      <div class="searchBox search-box-layout">
        <Row :gutter="24">
          <Col span="4">
            <div>
              <p class="label">{{$t('common.company')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.companyId" filterable clearable :placeholder="`${$t('common.selectInfo')}`"
                        @on-change="getBackupList($event)">
                  <Option v-for="(item) of companyList" :value="item.id" :key="item.code"  :label="item.fullName">
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('common.WarehouseNo')}}</p>
              <div class="ipt">
                <Select v-model="backupId" filterable clearable :placeholder="`${$t('common.selectInfo')}`"
                        @on-change="handleBackupSelect" @on-open-change="openBackupSelect">
                  <Option v-for="(item) of backupList" :value="item.id" :key="item.id" :label="item.backupNo+'-'+item.backupName">
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('spareParts.ReservoirNo')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.shelf" filterable clearable :placeholder="`${$t('common.selectInfo')}`"
                        @on-open-change="openShelfSelect">
                  <Option v-for="(item) of shelfList" :value="item.shelf" :key="item.id" :label="item.shelfNo+'-'+item.shelf">
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label hide-label">--</p>
              <div class="ipt">
                <Button class="search-btn" type="primary" v-if="checkBtnPermission.goodsShelvesList" @click="changeNum()">{{$t('common.Query')}}</Button>
                <Button class="reset-btn" @click="reset()" v-if="checkBtnPermission.goodsShelvesList"
                >{{ $t('common.reset') }}
                </Button>
              </div>
            </div>
          </Col>
        </Row>
      </div>
      <div class="list-layout mt16">
        <div class="btns clear">
          <span class="title">{{ $t('common.listInformation') }}</span>
          <Button  @click="createfaultCodeShowH" v-if="checkBtnPermission.goodsShelvesAdd">{{$t('common.New')}}</Button>
          <Button  @click="delFaultCodeShowClick" v-if="checkBtnPermission.goodsShelvesDelete">{{$t('common.batchDelete')}}</Button>
          <Button  @click="exportTemplateClick" v-if="checkBtnPermission.goodsShelvesExport">{{$t('common.batchExport')}}</Button>
          <Button  @click="importExcelShow" v-if="checkBtnPermission.goodsShelvesImport">{{$t('common.Import')}}</Button>
          <Button  @click="exportTemplate" v-if="checkBtnPermission.goodsShelvesTemplate">{{$t('common.Download')}}</Button>
          <Button @click="getTableColumns(columns)">{{ handleContextMenuStatus ? $t('显示操作栏') : $t('隐藏操作栏') }}</Button>
        </div>
        <div class="tableContent">
          <Table  class="resizable-table" border @on-column-width-resize="onColumnWidthResize"
                  :columns="columnsList" ellipsis ref="selection" stripe :data="dataArr"
                 @on-selection-change="onSelectChange">
            <template slot-scope="{ row }" slot="action">
                    <span class="operationBtn" @click="createfaultCodeShowH(row)"
                          v-if="checkBtnPermission.goodsShelvesEdit"><i class="iconfont zy-common-bianji"></i>{{ $t('common.Edit') }}</span>
              <span class="operationBtn" @click="delPrrShowH(row)"
                    v-if="checkBtnPermission.goodsShelvesDelete"><i class="iconfont zy-common-shanchu"></i>{{ $t('common.Delete') }}</span>
            </template>
          </Table>
        </div>
        <div class="pageWrap mt16">
          <pageLeftTitle :total="total" :selected="delIds.length"/>
          <Page :total="total" :page-size="pageSize" :page-size-opts="pageSizeOption" :current="pageNum"
                @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total />
        </div>
      </div>
        <Modal :mask-closable="false" v-model="create" :title="addtitle" class="modal-content-layout">
            <Form ref="form" v-if="create" class="formList" :model="formItem" label-position="top" :rules="ruleValidate">
                <!-- 公司 -->
                <FormItem :label="$t('common.company')" prop="companyId">
                    <Select v-model="formItem.companyId" filterable  :placeholder="`${$t('common.selectInfo')}`"
                         @on-change="getBackupList(formItem.companyId)">
                        <Option v-for="(item) of companyList" :value="item.id" :key="item.code" :label="item.name">
                        </Option>
                    </Select>
                </FormItem>
                 <!-- 仓库 -->
                <FormItem  :label="$t('spareParts.Warehouse')" prop="backupConfigId">
                    <Select v-model="formItem.backupConfigId" filterable  :placeholder="`${$t('common.selectInfo')}`"
                        @on-open-change="openBackupSelect">
                        <Option v-for="(item) of backupList" :value="item.id" :key="item.id" :label="item.backupNo+'-'+item.backupName">
                        </Option>
                    </Select>
                </FormItem>
                <!-- 货架 -->
                <FormItem  :label="$t('spareParts.ReservoirNo')" prop="shelfNo">
                    <Input type="text" v-model="formItem.shelf" :placeholder="`${$t('common.inputInfo')}`" :maxlength="32"></Input>
                </FormItem>
                <FormItem  :label="$t('spareParts.ReservoirName')" prop="shelf">
                    <Input type="text" v-model="formItem.shelfNo" :placeholder="`${$t('common.inputInfo')}`" :maxlength="32"></Input>
                </FormItem>
                 <!-- 备注 -->
                <FormItem :label="$t('common.remarks')">
                    <Input type="textarea" v-model="formItem.remark" :placeholder="`${$t('common.inputInfo')}`"
                        :autosize="{ minRows: 2, maxRows: 5 }"></Input>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="default" @click="create = false">{{ $t('common.Cancle') }}</Button>
                <Button type="primary" :loading="loading"
                    @click="addOk('form')">{{ $t('maintenance.Confirmed') }}</Button>
            </div>
        </Modal>
        <Modal :mask-closable="false" v-model="delFaultCodeShowF"  :title="$t('common.Delete')" class="modal-title-layout">
          <div class="icon red">
            <i class="iconfont zy-common-shanchu"></i>
          </div>
          <p class="title">
            <span>{{$t('common.confirmDelete')}}</span>
          </p>
            <div slot="footer">
                <Button type="default" @click="delFaultCodeShowF = false">{{ $t('common.Cancle') }}</Button>
                <Button type="primary" :loading="loading" @click="deleteOk">{{ $t('maintenance.Confirmed') }}</Button>
            </div>
        </Modal>
        <importExcelModal :importExcelStateF="importExcelState" v-if="importExcelState"
            @importExcelChange="importExcelChange"></importExcelModal>
    </div>
</template>

<script>
import { searchApi, addApi, editApi, deleteApi, templateApi, exportApi } from "@/api/spareParts/goodsShelves.js";
import { getUserSelect, getCompany, getBackup, getShelf, getLocation } from "@/api/index.js";
import importExcelModal from '@/components/importExcel.vue';
import fileDownload from 'js-file-download';
import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
    name: "goodsShelves",//货架配置
    components: { importExcelModal },
    mixins:[toggleTableOperation],
    data() {
        return {
            companyList: [],
            backupList: [],
            shelfList: [],
            importExcelState: false, /*批量导入*/
            formItem: {
                companyId: null,
                backupConfigId: null,
                shelf: null,
                shelfNo:null,
            },
            addtitle: "",
            allCheck: false,
            loading: false,
            create: false,
            searchParams: {},
            pageNum: 1,
            pageSize: 10,
            total: 0,
            columns: [
                {
                    key: 'selection',
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                   // title: '公司',
                     title: `${ this.$t('common.company') }`,
                    key: 'companyName',
                    minWidth: 150,
                    align: 'center',
                    resizable: true
                },
                {
                    //title: `${this.$t('spareParts.Warehouse')}`,
                    title: `${ this.$t('common.WarehouseNo') }`,
                    key: 'backupName',
                    minWidth: 130,
                    align: 'center',
                    resizable: true
                },
                {
                    //title: `${this.$t('spareParts.Warehouse')}`,
                    title: `${ this.$t('common.Warehouse') }`,
                    key: 'backupNo',
                    minWidth: 150,
                    align: 'center',
                    resizable: true
                },

                {
                   // title: `${this.$t('spareParts.Rack')}`,
                    title: `${ this.$t('spareParts.ReservoirNo') }`,
                    key: 'shelf',
                    minWidth: 150,
                    align: 'center',
                    resizable: true
                },
                {
                   // title: `${this.$t('spareParts.Rack')}`,
                    title: `${ this.$t('spareParts.ReservoirName') }`,
                    key: 'shelfNo',
                    minWidth: 140,
                    align: 'center',
                    resizable: true
                },

                {
                   // title: '管理员',
                    title: `${ this.$t('common.administrators') }`,
                    key: 'manageByName',
                    minWidth: 120,
                    align: 'center',
                    resizable: true
                },
                {
                    //title: '创建人',
                     title: `${ this.$t('common.CreateBy') }`,
                    key: 'createByName',
                    minWidth: 100,
                    align: 'center',
                    resizable: true
                },
                {
                    //title: '备注',
                     title: `${ this.$t('common.remarks') }`,
                    key: 'remark',
                    minWidth: 100,
                    align: 'center',
                    resizable: true
                },
                {
                   // title: '创建时间',
                     title: `${ this.$t('common.CreateTime') }`,
                    key: 'createTime',
                    minWidth: 150,
                    align: 'center',
                    resizable: true
                },
                {
                    title: `${this.$t('common.operation')}`,
                    slot: "action",
                    fixed: 'right',
                    minWidth: 200,
                    align: "center"
                }
            ],
            dataArr: [],
            delFaultCodeShowF: false,//是否显示删除弹窗
            pageSizeOption: [10, 20, 30, 40],
            delIds: [],
            selection: [],
            checkBtnPermission: {},
            createByOptions: [],
            backupId: '',
            ruleValidate: {
                companyId: [
                    { required: true, message: '请选择公司', trigger: 'blur', type: "number" }
                ],
                backupConfigId: [
                    { required: true, message: '请选择仓库', trigger: 'blur', type: "number" }
                ],
                shelf: [
                    { required: true, message: '请填写库区名称', trigger: 'blur', type: "string" }
                ],
                shelfNo: [
                    { required: true, message: '请填写库区编号', trigger: 'blur', type: "string" }
                ],
            }
        }
    },
    mounted() {

        this.getTableColumnsWidth(this.columns)

        this.searchList();
        this.getCompanyList();
        this.getUserList();
        let itemList = JSON.parse(window.localStorage.getItem('USER_URI'))
        for (let item of itemList) {
            if (item.code == "goodsShelvesList") {
                this.checkBtnPermission.goodsShelvesList = true
            }
            if (item.code == "goodsShelvesAdd") {
                this.checkBtnPermission.goodsShelvesAdd = true
            }
            if (item.code == "goodsShelvesDelete") {
                this.checkBtnPermission.goodsShelvesDelete = true
            }
            if (item.code == "goodsShelvesEdit") {
                this.checkBtnPermission.goodsShelvesEdit = true
            }
            if (item.code == "goodsShelvesExport") {
                this.checkBtnPermission.goodsShelvesExport = true
            }
            if (item.code == "goodsShelvesImport") {
                this.checkBtnPermission.goodsShelvesImport = true
            }
            if (item.code == "goodsShelvesTemplate") {
                this.checkBtnPermission.goodsShelvesTemplate = true
            }
        }

    },
        watch: {
        'searchParams.companyId': {
            handler(val, oldVal) {
                this.backupId = null
                this.$set(this.searchParams,'shelf',null)
                this.backupList = []
                this.shelfList = []
            },
            deep: true
        },
        backupId: {
            handler(val, oldVal) {
                this.$set(this.searchParams,'shelf',null)
                this.shelfList = []
            },
            deep: true
        },
    },
    methods: {
        //获取公司
        getCompanyList() {
            getCompany().then(res => {
                if (res.code === 200) {
                    this.companyList = res.data
                }
                // else {
                //     this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                // }
            }).finally(() => {
                this.loading = false
            })
        },
        //获取仓库
        async getBackupList(data) {
            this.formItem.backupConfigId = null
            this.backupList = []
            let params = {
                companyId: data
            }
            await getBackup(params).then(res => {
                if (res.code === 200) {
                    this.backupList = res.data
                }
                // else {
                //     this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                // }
            }).finally(() => {
                this.loading = false
            })
        },

        //   if(!this.searchParams.backupConfigId){
        //         this.$Message.warning(({ content:"请先选择仓库", duration: 6, closable: true }));
        //         return false;
        //     }
        openBackupSelect(isOpen) {
            if (isOpen === true) {
                if (!this.searchParams.companyId && !this.formItem.companyId) {
                    this.$Message.warning(({ content: "请先选择公司", duration: 6, closable: true }));
                    return false;
                }
            }
        },
        handleBackupSelect(data) {
            if (!data) {
                this.searchParams.backupName = ""
            }
            this.backupList.map((item, index) => {
                if (item.id == data) {
                    this.searchParams.backupName = item.backupName
                }
            })
            this.getShelfList(data)
        },
        openShelfSelect(isOpen) {
            if (isOpen === true) {
                if (!this.searchParams.backupName) {
                    this.$Message.warning(({ content: "请先选择仓库", duration: 6, closable: true }));
                    return false;
                }
            }
        },
        //获取货架
        getShelfList(data) {
            let params = {}
            params.delIds = []
            params.delIds.push(data)
            getShelf(params).then(res => {
                if (res.code === 200) {
                    this.shelfList = res.data
                }
                // else {
                //     this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                // }
            }).finally(() => {
                this.loading = false
            })
        },
        //获取管理员
        getUserList() {
            getUserSelect().then(res => {
                if (res.code === 200) {
                    this.createByOptions = res.data.map(item => {
                        return {
                            ...item,
                            showName: item.empno + '----' + item.username
                        }
                    })
                } else {
                    this.createByOptions = []
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            }).finally(() => {
                this.loading = false
            })
        },
      reset(){
          this.searchParams = {};
          this.changeNum();
      },
        //分页
        changeNum() {
            this.pageNum = 1;
            this.searchList();
        },
        changePageSize(pageSize) {
            this.pageSize = pageSize;
            this.searchList();
        },
        changePageNum(val) {
            this.pageNum = val;
            this.searchList();
        },
        //查询列表
        searchList() {
            let params = {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
            };
            for (let key in this.searchParams) {
                if (this.searchParams[key]) {
                    this.$set(params, key, this.searchParams[key])
                }
            }
            searchApi(params).then(res => {
                
                if (res.code === 200) {
                    this.dataArr = res.data.list
                    this.total = res.data.total
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            })
        },
        //增加或编辑
        createfaultCodeShowH(row) {
            //this.$refs.form.resetFields();
            if (row.id) {
                this.backupList=[],
                this.shelfList=[],
                //this.addtitle = `${this.$t('common.Edit')}`
               this.addtitle= `${this.$t('common.Edit')}`
                if (row.companyId) {
                    this.getBackupList(row.companyId)
                }
                this.formItem.id = row.id
                this.formItem.companyId = row.companyId
                this.formItem.backupConfigId = row.backupConfigId
                this.formItem.shelf = row.shelf
                this.formItem.shelfNo = row.shelfNo
                this.formItem.remark = row.remark
            } else {
                //this.addtitle = "新增"
                this.addtitle= `${this.$t('common.New')}`
                this.formItem = {
                    companyId: null,
                    backupConfigId: null,
                    shelf: null,
                    shelfNo:null,
                };
            }
            this.create = true;
        },
        addOk(name) {
            this.$refs[name].validate((valid) => {
                if (!valid) {
                    return
                } else {
                    console.log("ceshi")
                    this.loading = true;
                    if (this.formItem.id) {
                        editApi(this.formItem).then(res => {
                            this.loading = false; 0
                            if (res.code === 200) {
                                this.changeNum();
                                this.$Message.success("编辑成功");
                                this.create = false;
                            } else {
                                this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                            }
                        })
                    } else {
                        addApi(this.formItem).then(res => {
                            this.loading = false;
                            if (res.code === 200) {
                                this.changeNum();
                                this.$Message.success("新增成功");
                                this.create = false;
                            } else {
                                this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                            }
                        })
                    }
                }
            })

        },
        //勾选列表
        onSelectChange(selection) {
            let myArray = [];
            selection.map((item, index) => {
                myArray.push(item.id);
            });
            this.delIds = myArray;
            if (selection.length > 0) {
                this.allCheck = true;
            } else {
                this.allCheck = false;
            }
        },
        //批量删除
        delFaultCodeShowClick() {
            if (this.delIds.length == 0) {
                this.$Message.warning({
                    content:`${ this.$t('common.deleteItems') }`,
                    duration: 6,
                    closable: true,
                });
                return;
            } else {
                this.delFaultCodeShowF = true;
            }
        },
        //删除
        delPrrShowH(row) {
            //点击展示提示删除弹窗
            this.delFaultCodeShowF = true;
            this.delIds = [];
            this.delIds.push(row.id);
        },
        deleteOk() {
            this.loading = true;
            let params = { delIds: this.delIds }
            deleteApi(params).then(res => {
                this.loading = false;
                if (res.code === 200) {
                    this.changeNum();
                    this.$Message.success("删除成功");
                    this.allCheck = false;
                    this.delFaultCodeShowF = false;
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            })
        },
        //下载模板
        exportTemplate() {
            const filName = '货架配置模板'
            templateApi().then(res => {
                fileDownload(res, filName + '.xlsx')
            })
        },
        //导入
        importExcelShow() {
            this.importExcelState = true;
        },
        importExcelChange(val) {
            this.importExcelState = false;
            if (val === 'success') {
                this.changeNum();
            }
        },
        //导出
        exportTemplateClick() {
            let params = {
                delIds: this.delIds,
            };
            for (let key in this.searchParams) {
                if (this.searchParams[key]) {
                    this.$set(params, key, this.searchParams[key])
                }
            }
            const filName = '货架配置'
            exportApi(params).then(res => {
                fileDownload(res, filName + '.xlsx')
            })
        }
    }
}
</script>

<style scoped lang="scss">
.ivu-input-number {
    width: -webkit-fill-available;
}
</style>

